<?php

// ==============================================================================
//
// This file is part of the WelSpeak.
//
// Create by Welfony Support <support@welfony.com>
// Copyright (c) 2012-2014 welfony.com
//
// For the full copyright and license information, please view the LICENSE
// file that was distributed with this source code.
//
// ==============================================================================

namespace Welfony\Welspeak\Repository;

use Welfony\Welspeak\Core\Enum\MessageStatus;

class FriendRepository
{

    public static function findFriendByTwoIds($id1, $id2)
    {
        global $app;

        $strSql = 'SELECT
                       F.FriendId,
                       F.InvitorId,
                       U.Username InvitorUsername,
                       F.UserId,
                       F.CreatedDate
                   FROM Friend F
                   INNER JOIN Users U ON U.UserId = F.InvitorId
                   WHERE (F.InvitorId = ? AND F.UserId = ?) OR (F.UserId = ? AND F.InvitorId = ?)
                   LIMIT 1';

        return $app->conn->fetchAssoc($strSql, array($id1, $id2, $id1, $id2));
    }

    public static function getAllFriendsByUser($userId)
    {
        global $app;

        $strSql = "SELECT
                      US.UserId,
                      US.PIN,
                      US.Username,
                      US.AvatarUrl,
                      US.ProfileBackgroundUrl,
                      US.SocialExternalId,
                      US.SocialType,
                      COUNT(M.MessageId) NewMessageCount
                    FROM vwUserSocial US
                    LEFT OUTER JOIN Message M ON M.SenderId = US.UserId AND M.ReceiverId = ? AND M.Status = 1
                    WHERE US.UserId != ? AND (
                          US.UserId IN (SELECT FU.UserId FROM Friend FU WHERE FU.InvitorId = ?
                                        UNION
                                        SELECT FI.InvitorId FROM Friend FI WHERE FI.UserId = ?)
                    )
                    GROUP BY US.UserId
                    ORDER BY M.CreatedDate DESC, US.UserId DESC;";

        return $app->conn->fetchAll($strSql, array($userId, $userId, $userId, $userId));
    }

    public static function FindFriendsByUserAndSocial($userId, $socialExternalId, $socialType)
    {
        global $app;

        $strSql = "SELECT
                      US.UserId,
                      US.PIN,
                      US.Username,
                      US.AvatarUrl,
                      US.ProfileBackgroundUrl,
                      US.SocialExternalId,
                      US.SocialType
                    FROM vwUserSocial US
                    WHERE US.SocialExternalId = ? AND US.SocialType = ? AND (
                          US.UserId IN (SELECT FU.UserId FROM Friend FU WHERE FU.InvitorId = ?
                                        UNION
                                        SELECT FI.InvitorId FROM Friend FI WHERE FI.UserId = ?)
                    )
                    LIMIT 1;";

        return $app->conn->fetchAssoc($strSql, array($socialExternalId, $socialType, $userId, $userId));
    }

    public static function save($data)
    {
        global $app;

        try {
            if ($app->conn->insert('Friend', $data)) {
                return $app->conn->lastInsertId();
            }
        } catch (\Exception $e) {
            $app->log->getWriter()->write($e, \Slim\Log::ERROR);
            return false;
        }

        return false;
    }

    public static function update($friendId, $data)
    {
        global $app;

        try {
            return $app->conn->update('Friend', $data, array('FriendId' => $friendId));
        } catch (\Exception $e) {
            $app->log->getWriter()->write($e, \Slim\Log::ERROR);
            return false;
        }
    }

    public static function removeByInvitorAndUser($invitorId, $userId)
    {
        global $app;

        try {
            $app->conn->delete('Friend', array('InvitorId' => $invitorId, 'UserId' => $userId));
            $app->conn->delete('Friend', array('InvitorId' => $userId, 'UserId' => $invitorId));
            return true;
        } catch (\Exception $e) {
            $app->log->getWriter()->write($e, \Slim\Log::ERROR);
            return false;
        }
    }

}